﻿using CMS.Excep;

namespace CMS.Utils
{
    public static class ServiceLoader
    {
        internal static IServiceProvider? HttpServiceProvider { get; private set; }
        public static void InitHttpServiceProvider(IServiceProvider httpServiceProvider)
        {
            if (httpServiceProvider == null)
                throw new MyClassException("初始化ServiceProvider失败");
            HttpServiceProvider = httpServiceProvider;
        }
        public static HttpContext GetHttpContext()
        {
            return HttpServiceProvider.GetRequiredService<IHttpContextAccessor>()?.HttpContext;
        }
        public static OptUser GetOptUser()
        {
            return GetService<OptUser>();
        }
        public static T GetService<T>()
        {
            var httpContext = HttpServiceProvider.GetRequiredService<IHttpContextAccessor>()?.HttpContext;
            try
            {
                return httpContext!.RequestServices.GetService<T>();
            }
            catch (Exception ex)
            {
                throw new MyClassException($"创建CLASS={typeof(T)}出错", ex);
            }
        }
    }
}
